package com.wang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.mapper.AnnouncementMapper;
import com.wang.entity.Announcement;
import com.wang.service.AnnouncementService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 33115
 * @description 针对表【announcement】的数据库操作Service实现
 * @createDate 2024-06-17 11:12:44
 */
@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement>
        implements AnnouncementService {

    /**
     * 添加公告
     * @param announcement 待添加的公告对象
     */
    @Override
    public void addAnnouncement(Announcement announcement) {
        if (announcement == null || StringUtils.isAnyBlank(announcement.getTitle(), announcement.getContent())) {
            System.out.println("公告标题和内容不能为空");
        }
        save(announcement); // 使用MyBatis-Plus的save方法直接保存
    }

//    @Override
//    public List<Announcement> getAnnouncement(Integer announcementId) {
//        if (announcementId == null) {
//           System.out.println("公告ID不能为空");
//        }
//        LambdaQueryWrapper<Announcement> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Announcement::getAnnouncementId, announcementId);
//        return list(queryWrapper);
//    }
@Override
public List<Announcement> getAnnouncement(String title, LocalDateTime startDate, LocalDateTime endDate) {
    LambdaQueryWrapper<Announcement> queryWrapper = new LambdaQueryWrapper<>();
    System.out.println(StringUtils.isNotBlank(title));
    // 分别检查并设置查询条件
    if (StringUtils.isNotBlank(title)) {
        queryWrapper.like(Announcement::getTitle, "%" + title + "%"); // 根据标题模糊匹配
    }

    if (startDate != null && endDate != null) {
        queryWrapper.between(Announcement::getPublishTime, startDate, endDate); // 根据发布时间筛选
    }

    // 确保至少有一个查询条件被设置
    if (queryWrapper.isEmptyOfWhere()) {
        throw new IllegalArgumentException("至少需要提供标题关键词或时间范围进行查询");
    }

    return list(queryWrapper);
}

    /**
     * 更新公告
     * @param announcement 待更新的公告对象，需包含公告ID
     */
    @Override
    public void updateAnnouncement(Announcement announcement) {
        if (announcement.getTitle() == null || announcement.getContent() == null) {
            System.out.println("公告标题或内容不能为空");
        }
        updateById(announcement); // 使用MyBatis-Plus的updateById方法直接更新
    }

    /**
     * 删除公告
     * @param announcementId 公告ID
     */
    @Override
    public void deleteAnnouncement(Integer announcementId) {
        if (announcementId == null) {
           System.out.println("公告ID不能为空");
        }
        removeById(announcementId); // 使用MyBatis-Plus的removeById方法直接删除
    }
}